package com.bird.pro.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class SystemInterceptor implements HandlerInterceptor{
	Logger log = LoggerFactory.getLogger(SystemInterceptor.class);
	@Value("${system.prefix}")
	public String systemPrefix;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String path = request.getServletPath();
		if(!pathIsStartWith(path)){
			return true;
		}
		log.info("---------> 开始过滤");
		HttpSession session = request.getSession();
		if(session.getAttribute("admin") == null){
			response.sendRedirect("/");
			return false;
		}
		return true;
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
	
	private boolean pathIsStartWith(String path){
		for (String p : systemPrefix.split(",")) {
			if(path.startsWith("/" + p)){
				return true;
			}
		}
		return false;
	}
	
	
}
